package org.dss.gil.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * This is the generic class to interact with the command line (CMD)
 * you only need to create an instance and execute your command.
 * @author fernando.gil
 * @since September 2012
 * @version 1.1
 */

public class CmdConnector {

    private BufferedReader inputStream;
    private BufferedReader errorStream;
    private String inputString;
    private String errorString;
    private String operatingSystem;
    private Process process;
    
    public CmdConnector(){
        operatingSystem = System.getProperty("os.name");        
    }
    
    public BufferedReader getErrorStream() {
        return errorStream;
    }

    public BufferedReader getInputStream() {
        return inputStream;
    }

    public Process getProcess() {
        return process;
    }

    public String getOperatingSystem() {
        return operatingSystem;
    }

    public String getErrorString() {
        return errorString;
    }

    public String getInputString() {
        return inputString;
    }
    
    public void executeCommand(String command) throws IOException, GiGenericException{
        if(isWindowsSystem()){
            process = Runtime.getRuntime().exec(command);
            inputStream = new BufferedReader(new InputStreamReader( process.getInputStream() ));
            errorStream = new BufferedReader(new InputStreamReader( process.getErrorStream() ));
            inputString = readStream(inputStream);
            errorString = readStream(errorStream);
        }else{
            throw new GiGenericException( Globals.language.getMessage("message.sim.os") );
        }
    }

    private String readStream(BufferedReader stream) throws IOException {
        StringBuilder content = new StringBuilder();
        String line;
        while ( (line = stream.readLine()) != null) {
            content.append(line).append( "\n" );
        }
        return content.toString();
    }
    
    private boolean isWindowsSystem(){
        return ( operatingSystem.toUpperCase().indexOf( "WINDOWS" ) >= 0 );
    }
    
}
